package com.cssy.yd.logic.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.mf.enums.WhCheckStatusEnum;
import com.cssy.xxkj.logic.entity.LogicWhCheckTaskDO;
import com.cssy.xxkj.logic.entity.LogicWhCheckTaskItemDO;
import com.cssy.xxkj.logic.service.ILogicWhCheckTaskService;
import com.cssy.yd.logic.entity.LogicWhCheckMissionItemDO;
import com.cssy.yd.logic.service.ILogicWhCheckMissionService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.ExcelUtil;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;

@Controller
@RequestMapping("/yd/logic/whcheckmission")
public class WHCheckMissionController extends BaseController<LogicWhCheckTaskDO> {
	private static final String MANAGER = "/yd/logic/pandian/WHCheckMissionManager";// 列表页面
	private static final String EIDT = "/yd/logic/pandian/WHCheckMissionOperation";// 添加、修改、显示页面
	private static final String TASK = "/yd/logic/pandian/WHCheckTaskItemOperation";//盘点修改
	
	@Resource(name = "logicWhCheckMissionService")
	private ILogicWhCheckMissionService logicWhCheckMissionService;

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Resource(name="logicWhCheckTaskService")
	private ILogicWhCheckTaskService logicWhCheckTaskService; 


	public String manager(HttpServletRequest request, Model model)//新建盘点任务
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("checkStatus", WhCheckStatusEnum.values());
		model.addAttribute("checkTask", "noselect");
		return MANAGER;
	}
	@RequestMapping("/checkTask")//盘点
	public String checkTask(HttpServletRequest request, Model model){
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("checkStatus", WhCheckStatusEnum.values());
		model.addAttribute("checkTask", "select");
		return MANAGER;
	}
	@RequestMapping("/check")
	public String check(HttpServletRequest request, Model model){
		
		
		
		/*model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("checkStatus", WhCheckStatusEnum.values());
		model.addAttribute("checkTask", "check");
		String obj=request.getParameter("data");
		if(obj!=null&&obj.length()>0){
			String[] ids=obj.split(",");
			for(String id:ids){//根据每一个的id设置为盘点中状态
				LogicWhCheckTaskDO lct= new LogicWhCheckTaskDO();
				lct=logicWhCheckTaskService.findListById(id);
				lct.setZd003BillStatus("2");
				logicWhCheckTaskService.update(lct,SessionUtil.getUser(request));
			}
		}*/
		return TASK;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		String check=request.getParameter("checkTask");
		hander.getWheres(scs);	
		if(check!=null&&check.equals("select")){//去盘点
			List<String> list=new ArrayList<String>();
			list.add("1");//未盘点
			list.add("5");//驳回重盘
			scs.addCondition("zd003BillStatus", list);
		}
		if(check!=null&&check.equals("check")){//盘点中
			scs.addCondition("zd003BillStatus", "2");
		}
		scs.setRemovedProperty(null);
		scs.setOrderBy("bizCreatorDate desc");
		scs.addCondition("removed", 0l);
		//获得当前用户拥有权限的仓库
		Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request,  scUserRolePlaceService,"zd001WhCode");

		scs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		//SearchResult result = logicWhCheckMissionService.findListByExample(scs);
		SearchResult result =logicWhCheckTaskService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
					throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
			model.addAttribute("xx", "1");
		} else {
			//LogicWhCheckMissionDO lpd = logicWhCheckMissionService.findListById(id);
			LogicWhCheckTaskDO lpd=logicWhCheckTaskService.findListById(id);
			String check=request.getParameter("checkTask");
			//List<LogicWhCheckMissionItemDO> pditemlist = logicWhCheckMissionService.findItemListByCheckMissionID(lpd.getId());
			/**
			 * 盘点人鼻必须为制单人？（制定盘点任务）
			 */
			/*if(check.equals("check")){//盘点时
				lpd.setZd004Agent(SessionUtil.getUser(request).getName());//设置盘点人为当前用户
			}
			if("0".equals(lpd.getZd003BillStatus()) ) {
				model.addAttribute("flag", "tijiao");
			} 
			if("1".equals(lpd.getZd003BillStatus())) {
				model.addAttribute("flag", "weipandian");
			}
			if("2".equals(lpd.getZd003BillStatus())) {
				model.addAttribute("flag", "pandianzhong");
			}
			if("3".equals(lpd.getZd003BillStatus())) {
				model.addAttribute("flag", "shenhe");
			}
			if("4".equals(lpd.getZd003BillStatus())) {
				model.addAttribute("flag", "complete");
			}
			if("5".equals(lpd.getZd003BillStatus())) {
				model.addAttribute("flag", "chongpan");
			}*/
			model.addAttribute("pd", lpd);
			//model.addAttribute("pditemlist", pditemlist);
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}

	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicWhCheckTaskDO lct=logicWhCheckTaskService.findListById(id);
			List<LogicWhCheckTaskItemDO> pditemlist=logicWhCheckTaskService.findItemListByCheckTsdkID(lct.getId());
			OutJsonGrid out = new OutJsonGrid(pditemlist);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicWhCheckTaskDO curAP, BindingResult result, Model model)
					throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String checkdata = request.getParameter("checkdata");
		if (checkdata == null && "".equals(checkdata)) {
			bodyMap.isFail();
			bodyMap.configWebInfor("盘点内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			logicWhCheckTaskService.checkTaskSave(request, curAP);
			//			logicWhCheckMissionService.checksave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}


	/*@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String, String> map=new HashMap<String, String>();
		try{
			String id = request.getParameter("id");
			if(id!=null&&!"".equals(id)){
				LogicWhCheckMissionDO lcm = logicWhCheckMissionService.findListById(id);
				if(lcm.getId()!=null){
					lcm.setBillStatus(2); //直接驳回到盘点中状态
					logicWhCheckMissionService.update(lcm, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}*/

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				//				LogicWhCheckMissionDO ld = logicWhCheckMissionService.findListById(field);
				LogicWhCheckTaskDO ld=logicWhCheckTaskService.findListById(field);
				if (ld != null) {
					ld.setRemoved(1l);
					//					logicWhCheckMissionService.update(ld, SessionUtil.getUser(request));
					logicWhCheckTaskService.update(ld, SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	@RequestMapping("/exportExcel")
	public void exportAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//		String itemdata = request.getParameter("itemdata");
		//		List<LogicWhCheckMissionItemDO> list = null;
		//		if(itemdata!=null){
		//			list = JSONArray.parseArray(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"),LogicWhCheckMissionItemDO.class);
		//		}
		String checkmissionid = request.getParameter("checkmissionid");
		List<LogicWhCheckMissionItemDO> list = logicWhCheckMissionService.findItemListByCheckMissionID(checkmissionid);
		for(LogicWhCheckMissionItemDO itemdo :list){
			//将盘点数量和差异数量设为0
			Double tempquantity = new Double("0.0");
			itemdo.setQuantityPD(tempquantity);
			itemdo.setQuantityCY(tempquantity);
			itemdo.setYdengQuantityPD(tempquantity);
			itemdo.setYdengQuantityCY(tempquantity);
			itemdo.setCipinQuantityPD(tempquantity);
			itemdo.setCipinQuantityCY(tempquantity);
			itemdo.setJiupinQuantityPD(tempquantity);
			itemdo.setJiupinQuantityCY(tempquantity);
			itemdo.setFreezeQuantityPD(tempquantity);
			itemdo.setFreezeQuantityCY(tempquantity);
		}
		ExcelUtil.toExcel(list, "物料编码:code┋物料名称:name┋物料类型:maType┋型号:spec┋批次:batch┋单位:unit┋总库存数量:quantityWH┋总盘点数量:quantityPD┋总差异数量:quantityCY┋一等品库存数量:ydengQuantityWH┋一等品盘点数量:ydengQuantityPD┋一等品差异数量:ydengQuantityCY┋次品库存数量:cipinQuantityWH┋次品盘点数量:cipinQuantityPD┋次品差异数量:cipinQuantityCY┋旧品库存数量:jiupinQuantityWH┋旧品盘点数量:jiupinQuantityPD┋旧品差异数量:jiupinQuantityCY┋冻结库存数量:freezeQuantityWH┋冻结盘点数量:freezeQuantityPD┋冻结差异数量:freezeQuantityCY┋备注:remark","盘点任务导出",response);
	}

}
